package com.woniu.service;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.woniu.utils.SSHUtils;
import com.woniu.utils.SftpUtil;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

@Service
public class AudioProcessingService {

    @Value("${remote.ecs.host}")
    private String ecsHost;

    @Value("${remote.ecs.username}")
    private String ecsUsername;

    @Value("${remote.ecs.password}")
    private String ecsPassword;

    @Value("${remote.work.dir:/tmp/audio_processing}")
    private String remoteWorkDir;

    @Value("${local.temp.dir:temp}")
    private String localTempDir;
    public String processVideoToAudio(MultipartFile videoFile) throws IOException, JSchException, SftpException {
        // 1. 保存上传的文件到本地临时目录
        String originalFilename = videoFile.getOriginalFilename();
        String fileExtension = FilenameUtils.getExtension(originalFilename);
        String baseName = FilenameUtils.getBaseName(originalFilename);

        String uniqueId = UUID.randomUUID().toString();
        String localInputPath = localTempDir + File.separator + baseName + "_" + uniqueId + "." + fileExtension;
        String localOutputPath = localTempDir + File.separator + baseName + "_" + uniqueId + ".mp3";

        File localInputFile = new File(localInputPath);
        FileUtils.writeByteArrayToFile(localInputFile, videoFile.getBytes());

        // 2. 上传文件到ECS
        SftpUtil.uploadFile(ecsHost, ecsUsername, ecsPassword,
                localInputPath, remoteWorkDir);

        // 3. 构建远程文件路径
        String remoteInputPath = remoteWorkDir + "/" + localInputFile.getName();
        String remoteOutputPath = remoteWorkDir + "/" + baseName + "_" + uniqueId + ".mp3";

        // 4. 执行FFmpeg转换命令
        String command = String.format(
                "/usr/bin/ffmpeg6 -i \"%s\" -vn -acodec libmp3lame -q:a 2 \"%s\"",
                remoteInputPath, remoteOutputPath
        );

        SSHUtils.executeRemoteCommand(ecsHost, ecsUsername, ecsPassword, command);

        // 5. 下载生成的音频文件
        SftpUtil.downloadFile(ecsHost, ecsUsername, ecsPassword,
                remoteOutputPath, localTempDir);

        // 6. 清理远程文件
        cleanupRemoteFiles(remoteInputPath, remoteOutputPath);
        File localOutputFile = new File(localOutputPath);
        return localOutputPath;
        // 新增：将生成的音频文件封装为 MultipartFile
//        return new MockMultipartFile(
//                "file", // 表单字段名称
//                localOutputFile.getName(), // 文件名
//                "audio/mpeg", // 文件内容类型（可选）
//                new FileInputStream(localOutputFile) // 文件输入流
//        );
    }

    private void cleanupRemoteFiles(String... remotePaths) {
        try {
            StringBuilder command = new StringBuilder("rm -f");
            for (String path : remotePaths) {
                command.append(" \"").append(path).append("\"");
            }
            SSHUtils.executeRemoteCommand(ecsHost, ecsUsername, ecsPassword, command.toString());
        } catch (Exception e) {
            // 清理失败不影响主流程
        }
    }
//流式
//    public Mono<File> processVideoToAudio(FilePart videoFile) throws IOException, JSchException, SftpException {
//        // 1. 生成唯一文件名
//        String originalFilename = videoFile.filename();
//        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
//        String baseName = originalFilename.substring(0, originalFilename.lastIndexOf('.'));
//
//        String uniqueId = UUID.randomUUID().toString();
//        String localInputPath = localTempDir + File.separator + baseName + "_" + uniqueId + "." + fileExtension;
//        String localOutputPath = localTempDir + File.separator + baseName + "_" + uniqueId + ".mp3";
//
//        // 2. 异步保存上传的文件到本地
//        Path inputPath = Paths.get(localInputPath);
//        return videoFile.transferTo(inputPath.toFile())
//                .then(Mono.fromCallable(() -> {
//                    // 3. 上传到ECS
//                    SftpUtil.uploadFile(ecsHost, ecsUsername, ecsPassword,
//                            localInputPath, remoteWorkDir);
//
//                    // 4. 构建远程路径
//                    String remoteInputPath = remoteWorkDir + "/" + inputPath.getFileName();
//                    String remoteOutputPath = remoteWorkDir + "/" + baseName + "_" + uniqueId + ".mp3";
//
//                    // 5. 执行FFmpeg命令
//                    String command = String.format(
//                            "/usr/bin/ffmpeg6 -i \"%s\" -vn -acodec libmp3lame -q:a 2 \"%s\"",
//                            remoteInputPath, remoteOutputPath
//                    );
//                    SSHUtils.executeRemoteCommand(ecsHost, ecsUsername, ecsPassword, command);
//
//                    // 6. 下载音频文件
//                    SftpUtil.downloadFile(ecsHost, ecsUsername, ecsPassword,
//                            remoteOutputPath, localTempDir);
//
//                    // 7. 清理远程文件
//                    cleanupRemoteFiles(remoteInputPath, remoteOutputPath);
//
//                    return new File(localOutputPath);
//                }));
//    }
//
//    private void cleanupRemoteFiles(String... remotePaths) {
//        try {
//            StringBuilder command = new StringBuilder("rm -f");
//            for (String path : remotePaths) {
//                command.append(" \"").append(path).append("\"");
//            }
//            SSHUtils.executeRemoteCommand(ecsHost, ecsUsername, ecsPassword, command.toString());
//        } catch (Exception e) {
//            // 清理失败不影响主流程
//        }
//    }
}
